#!/bin/sh
[ -z "$CONFIG" ] && CONFIG=./config
. "$CONFIG"
export H="$PWD"

if [ -z "$R" ] ; then
	echo 'no R environment var set, your config is broken'
	exit 1
fi

mkdir -p "$R"/src/tarballs
linux32=
if [ $(uname -m) = "x86_64" ] && [ "$A" = i386 ] ; then
	[ -x ./linux32 ] && linux32=./linux32 || {
		$CC KEEP/linux32.c -static -s -Os -o ./linux32 && linux32=./linux32 || \
		echo -ne "warning: trying to chroot into i386 rootfs on x86_64" \
		         "kernel and building linux32 command failed\n"
	}
fi

if [ ! -z "$SUPER" ] ; then
	CHROOT=./super_chroot
	if [ ! -x "$CHROOT" ] ; then
		printf "super_chroot binary not found, compile KEEP/super_chroot.c\n"
		printf "musl-gcc KEEP/super_chroot.c -o super_chroot\n"
		exit 1
	fi
else

	uid="$(id -u)"
	if [ "$uid" != "0" ]; then
	    printf -- "need to be root. please enter password.\n"
	    su -c "$0"
	    exit $?
	fi


	mount --bind /dev "$R"/dev
	mount --bind /dev/pts "$R"/dev/pts
	mount --bind /dev/shm "$R"/dev/shm
	mount --bind /proc "$R"/proc
	mount --bind "$C" "$R"/src/tarballs

	CHROOT=chroot
fi

set_title() {
	[ "$TERM" != "linux" ] && [ "$TERM" != "vt100" ] && \
	echo -en "\033]2;$1\007"
}

set_title "SABOTAGE CHROOT $(basename $R)"

echo "Entering chroot..."

$linux32 "$CHROOT" "$R" /bin/env -i \
    HOME=/root TERM="$TERM" PS1='\u:\w$ ' \
    /bin/sh --login

tryumount() {
	dest="$1"
	if ! umount "$dest" 2>/dev/null; then
		echo "unmount failure ($dest), retrying in 1 sec..."
		sleep 1
		if ! umount -f "$dest" 2>/dev/null; then
		  echo "unmount -f failure ($dest), trying last resort umount -l"
		  umount -l "$dest"
		fi
	fi
}

if [ -z "$SUPER" ] ; then
	tryumount "$R"/src/tarballs
	tryumount "$R"/dev/pts
	tryumount "$R"/dev/shm
	tryumount "$R"/dev
	tryumount "$R"/proc
fi

set_title "sabotage"

#echo empty line so we get a proper prompt back
echo

